import { DIContainer } from '../infrastructure/di';
import { UnifiedServiceRegistry } from './base/UnifiedServiceRegistry';
import { ServiceMigrationManager, MIGRATION_PLANS, MigrationPhase } from './base/ServiceMigrationPlan';
import { UnifiedBagService } from './UnifiedBagService';

/**
 * 服务层统一重构实施
 * 负责协调和执行整个服务层的统一重构工作
 */
export class ServiceLayerUnification {
    private container: DIContainer;
    private unifiedRegistry: UnifiedServiceRegistry;
    private migrationManager: ServiceMigrationManager;
    private isInitialized = false;

    constructor(container: DIContainer) {
        this.container = container;
        this.unifiedRegistry = UnifiedServiceRegistry.getInstance(container);
        this.migrationManager = ServiceMigrationManager.getInstance(this.unifiedRegistry);
    }

    /**
     * 开始服务层统一重构
     */
    async startUnification(): Promise<void> {
        if (this.isInitialized) {
            console.warn('Service layer unification already started');
            return;
        }

        console.log('🚀 Starting Service Layer Unification...');
        console.log('============================================');
        
        try {
            // 第一步：注册所有统一服务
            await this.registerUnifiedServices();
            
            // 第二步：设置迁移计划
            await this.setupMigrationPlans();
            
            // 第三步：开始渐进式迁移
            await this.startProgressiveMigration();
            
            // 第四步：设置监控和健康检查
            await this.setupMonitoring();
            
            this.isInitialized = true;
            console.log('✅ Service Layer Unification completed successfully');
            
        } catch (error) {
            console.error('❌ Service Layer Unification failed:', error);
            throw error;
        }
    }

    /**
     * 注册所有统一服务
     */
    private async registerUnifiedServices(): Promise<void> {
        console.log('📋 Registering unified services...');
        
        // 注册统一服务（批量注册）
        this.unifiedRegistry.registerBatch([
            {
                name: 'UnifiedBagService',
                factory: (container) => new UnifiedBagService(container, {
                    enabled: true,
                    timeout: 10000,
                    maxRetries: 3,
                    healthCheckInterval: 30000
                }),
                config: {
                    singleton: true,
                    lifecycle: 'lazy', // 延迟初始化，等待迁移开始
                    priority: 10,
                    enableHealthCheck: true
                }
            },
            // 可以在这里添加更多统一服务
            // {
            //     name: 'UnifiedRPGService',
            //     factory: (container) => new UnifiedRPGService(container),
            //     config: { singleton: true, lifecycle: 'lazy', priority: 9 }
            // },
            // {
            //     name: 'UnifiedTalentService', 
            //     factory: (container) => new UnifiedTalentService(container),
            //     config: { singleton: true, lifecycle: 'lazy', priority: 8 }
            // }
        ]);

        console.log('✅ Unified services registered successfully');
    }

    /**
     * 设置迁移计划
     */
    private async setupMigrationPlans(): Promise<void> {
        console.log('📋 Setting up migration plans...');
        
        // 开始BagService迁移
        this.migrationManager.startMigration(MIGRATION_PLANS.BAG_SERVICE);
        
        // 注册回滚处理器
        this.migrationManager.registerRollbackHandler('BagService', async () => {
            console.log('🔄 Rolling back BagService migration...');
            // 这里可以添加具体的回滚逻辑
            // 例如：清理统一服务的状态，重新启用旧服务等
        });
        
        // 可以添加其他服务的迁移计划
        // this.migrationManager.startMigration(MIGRATION_PLANS.RPG_SERVICE);
        // this.migrationManager.startMigration(MIGRATION_PLANS.TALENT_SERVICE);
        
        console.log('✅ Migration plans setup completed');
    }

    /**
     * 开始渐进式迁移
     */
    private async startProgressiveMigration(): Promise<void> {
        console.log('🔄 Starting progressive migration...');
        
        // 阶段1：准备阶段 - 初始化统一服务但不启用
        await this.executeMigrationPhase('BagService', MigrationPhase.PREPARATION, 0);
        
        // 等待一段时间，让系统稳定
        await this.delay(2000);
        
        // 阶段2：双写阶段 - 新旧服务并行运行，但只有旧服务处理请求
        await this.executeMigrationPhase('BagService', MigrationPhase.DUAL_WRITE, 0);
        
        console.log('✅ Progressive migration started (Phase: DUAL_WRITE)');
        console.log('💡 To continue migration, use the migration management methods');
    }

    /**
     * 执行迁移阶段
     */
    private async executeMigrationPhase(serviceName: string, phase: MigrationPhase, trafficPercentage: number): Promise<void> {
        console.log(`🔄 Executing migration phase for ${serviceName}: ${phase} (${trafficPercentage}%)`);
        
        try {
            // 更新迁移阶段
            this.migrationManager.updateMigrationPhase(serviceName, phase, trafficPercentage);
            
            // 如果需要启用统一服务，进行初始化
            if (trafficPercentage > 0) {
                const unifiedService = this.unifiedRegistry.getService(serviceName.replace('Service', '') + 'UnifiedService');
                if (unifiedService && unifiedService.lifecycle === 'created') {
                    await unifiedService.init();
                    console.log(`✅ Unified service initialized: ${serviceName}`);
                }
            }
            
        } catch (error) {
            console.error(`❌ Failed to execute migration phase for ${serviceName}:`, error);
            // 自动回滚
            await this.migrationManager.triggerRollback(serviceName, `Phase execution failed: ${(error as Error).message}`);
            throw error;
        }
    }

    /**
     * 设置监控和健康检查
     */
    private async setupMonitoring(): Promise<void> {
        console.log('📊 Setting up monitoring and health checks...');
        
        // 设置定期迁移状态检查
        setInterval(() => {
            this.checkMigrationHealth();
        }, 60000); // 每分钟检查一次
        
        // 设置定期生成迁移报告
        setInterval(() => {
            this.generateAndLogMigrationReport();
        }, 300000); // 每5分钟生成一次报告
        
        console.log('✅ Monitoring setup completed');
    }

    /**
     * 检查迁移健康状态
     */
    private checkMigrationHealth(): void {
        const allStatus = this.migrationManager.getAllMigrationStatus();
        
        for (const [serviceName, status] of allStatus.entries()) {
            const totalCalls = status.successCount + status.errorCount;
            if (totalCalls > 0) {
                const errorRate = status.errorCount / totalCalls;
                
                if (errorRate > 0.05) { // 错误率超过5%
                    console.warn(`⚠️ High error rate detected for ${serviceName}: ${(errorRate * 100).toFixed(2)}%`);
                }
                
                if (status.avgResponseTime > 5000) { // 平均响应时间超过5秒
                    console.warn(`⚠️ High response time detected for ${serviceName}: ${status.avgResponseTime.toFixed(2)}ms`);
                }
            }
        }
    }

    /**
     * 生成并记录迁移报告
     */
    private generateAndLogMigrationReport(): void {
        const report = this.migrationManager.generateMigrationReport();
        console.log('📊 Migration Status Report:');
        console.log(report);
    }

    // ==================== 公共管理方法 ====================

    /**
     * 推进迁移到下一阶段
     */
    async advanceMigration(serviceName: string, trafficPercentage?: number): Promise<void> {
        const status = this.migrationManager.getMigrationStatus(serviceName);
        if (!status) {
            throw new Error(`Migration not found for service: ${serviceName}`);
        }
        
        const currentPhase = status.config.currentPhase;
        let nextPhase: MigrationPhase;
        let nextTraffic = trafficPercentage;
        
        switch (currentPhase) {
            case MigrationPhase.PREPARATION:
                nextPhase = MigrationPhase.DUAL_WRITE;
                nextTraffic = nextTraffic || 0;
                break;
            case MigrationPhase.DUAL_WRITE:
                nextPhase = MigrationPhase.TESTING;
                nextTraffic = nextTraffic || 10; // 默认10%流量
                break;
            case MigrationPhase.TESTING:
                nextPhase = MigrationPhase.SWITCHING;
                nextTraffic = nextTraffic || 50; // 默认50%流量
                break;
            case MigrationPhase.SWITCHING:
                nextPhase = MigrationPhase.CLEANUP;
                nextTraffic = nextTraffic || 100; // 默认100%流量
                break;
            case MigrationPhase.CLEANUP:
                nextPhase = MigrationPhase.COMPLETED;
                nextTraffic = 100;
                break;
            default:
                throw new Error(`Cannot advance from phase: ${currentPhase}`);
        }
        
        await this.executeMigrationPhase(serviceName, nextPhase, nextTraffic);
        console.log(`✅ Migration advanced for ${serviceName}: ${nextPhase} (${nextTraffic}%)`);
    }

    /**
     * 回滚迁移
     */
    async rollbackMigration(serviceName: string, reason: string): Promise<void> {
        await this.migrationManager.triggerRollback(serviceName, reason);
        console.log(`🔄 Migration rolled back for ${serviceName}: ${reason}`);
    }

    /**
     * 获取迁移状态
     */
    getMigrationStatus(serviceName?: string) {
        if (serviceName) {
            return this.migrationManager.getMigrationStatus(serviceName);
        }
        return this.migrationManager.getAllMigrationStatus();
    }

    /**
     * 完成迁移
     */
    async completeMigration(serviceName: string): Promise<void> {
        this.migrationManager.completeMigration(serviceName);
        
        // 可以在这里添加清理旧服务的逻辑
        console.log(`🎉 Migration completed for ${serviceName}`);
        console.log('💡 You can now safely remove the legacy service implementation');
    }

    /**
     * 获取服务健康状态
     */
    async getServiceHealth(): Promise<Map<string, any>> {
        return await this.unifiedRegistry.performGlobalHealthCheck();
    }

    /**
     * 获取统一注册表
     */
    getUnifiedRegistry(): UnifiedServiceRegistry {
        return this.unifiedRegistry;
    }

    /**
     * 延迟工具方法
     */
    private delay(ms: number): Promise<void> {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

/**
 * 导出单例实例创建函数
 */
export function createServiceLayerUnification(container: DIContainer): ServiceLayerUnification {
    return new ServiceLayerUnification(container);
}
